/* OTA example

   This example code is in the Public Domain (or CC0 licensed, at your option.)

   Unless required by applicable law or agreed to in writing, this
   software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
   CONDITIONS OF ANY KIND, either express or implied.
*/
#include "esp_log.h"
#include "freertos/projdefs.h"
#include "nvs.h"
#include "nvs_flash.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"

#include "my_wifi.h"
#include "app_http.h"

static const char *TAG = "main";

static void net_task(void *arg);

void app_main(void)
{
    ESP_LOGI(TAG, "OTA example app_main start");
    // Initialize NVS.
    esp_err_t err = nvs_flash_init();
    if (err == ESP_ERR_NVS_NO_FREE_PAGES || err == ESP_ERR_NVS_NEW_VERSION_FOUND)
    {
        // 1.OTA app partition table has a smaller NVS partition size than the non-OTA
        // partition table. This size mismatch may cause NVS initialization to fail.
        // 2.NVS partition contains data in new format and cannot be recognized by this version of code.
        // If this happens, we erase NVS partition and initialize NVS again.
        ESP_ERROR_CHECK(nvs_flash_erase());
        err = nvs_flash_init();
    }
    ESP_ERROR_CHECK(err);

    xTaskCreate(net_task, "net_task", 1024 * 5, NULL, 12, NULL);

    wifi_state_t result = wifi_wait_result((_BIT(connect_success_wifi)),
                              portMAX_DELAY);
    // http_get_request();
    // https_request();
    native_ota_test();
}

static void net_task(void *arg)
{
    uint8_t success_connect_before = 0;
    char user_id_ssid_str[10] = {0};
    char default_ssid_str[10] = "WENBENTEC";
    ESP_LOGE("NET_TAG", "net_task Startup..");
    wifi_init();
    while (!wifi_is_inited())
    {
        vTaskDelay(pdMS_TO_TICKS(1000));
    }
    ESP_LOGE("NET_TAG", "connect error , try with default ssid");

    modify_wificonfig_ssid(default_ssid_str);
    start_sta_wifi();
    wifi_state_t result = wifi_wait_result((_BIT(connect_failed_wifi) | _BIT(connect_success_wifi)),
                              portMAX_DELAY);
    if (result == connect_success_wifi)
    {
        ESP_LOGE("NET_TAG", "connect success with default ssid");
        success_connect_before = 1;
    }
    else
    {
        ESP_LOGE("NET_TAG", "connect failed with default ssid");
    }

    if (success_connect_before == 0)
    {
        vTaskDelete(NULL);
    }
    while (1)
    {
        result = wifi_wait_result(_BIT(connect_failed_wifi), portMAX_DELAY);
        set_wifi_state(nostart_wifi);
        vTaskDelay(pdMS_TO_TICKS(2000));
        start_sta_wifi();
    }
}
